<template>
  <n-form>
    <n-form-item label="标题">
      <n-input v-model:value="updateArticle.title" placeholder="请输入标题" />
    </n-form-item>
    <n-form-item label="分类">
      <n-select
        v-model:value="updateArticle.categoryId"
        :options="categortyOptions"
        placeholder="请选择分类"
      />
    </n-form-item>
    <n-form-item label="内容">
      <rich-text-editor v-model="updateArticle.content"></rich-text-editor>
    </n-form-item>
    <n-form-item label="">
      <n-button @click="update">提交</n-button>
    </n-form-item>
  </n-form>
</template>
<script setup>
import RichTextEditor from "@/components/RichTextEditor.vue";
import { reactive, defineExpose, ref, inject } from "vue";
const axios = inject("axios");
const message = inject("message");

const props = defineProps({
  // editBlogId: {
  //   type: [String, Number],
  //   default: null,
  // },
  categortyOptions: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['to-blog-list'])

// 文章数据
const updateArticle = reactive({
  id:null,
  categoryId: null,
  title: "",
  content: "",
});



// 加载播客详情
const loadBlogDetail = async (id) => {
  updateArticle.id = id
  try {
    const res = await axios.get(`/blog/detail?id=${id}`);
    if (res.data.code == 200) {
      let blog = res.data.data;
      console.log(blog);
      updateArticle.categoryId = blog.category_id;
      updateArticle.title = blog.title;
      updateArticle.content = blog.content;
    } else {
      message.error(res.data.msg);
    }
  } catch (err) {
    message.error(err);
  }
};

const update = async () => {
  if(!updateArticle.id) {
    message.error("请先选择博客")
    return
  }
  try {
    let res = await axios.put("/blog/_token/update", {
      categoryId: updateArticle.categoryId,
      title: updateArticle.title,
      content: updateArticle.content,
      id: updateArticle.id,
    });
    if (res.data.code == 200) {
      message.info(res.data.msg);
      emit("to-blog-list")
    } else {
      message.error(res.data.msg);
    }
  } catch (err) {
    message.error(err);
  }
};

defineExpose({
  loadBlogDetail,
});
</script>
<style lang="scss"></style>
